<template>
    <div class="dialog">
        <el-dialog
            title="视频上传"
            :visible.sync="videoFormVisible"
            :before-close="handleClose"
            width="700px"
            custom-class="hot-video-dialog">
            <el-divider></el-divider>
            <el-form
                :model="formData"
                :rules="rules"
                ref="uploadVideo"
                label-width="100px"
                label-position="right"
                size="small"
                style="width: 100%"
            >
                <el-form-item label="视频标题" prop="videoTitle">
                    <el-input v-model="formData.videoTitle" placeholder="请输入标题名称"></el-input>
                </el-form-item>
                <el-form-item label="视频分类" prop="videoClassId">
                    <el-select
                        v-model="formData.videoClassId"
                        placeholder="请选择"
                        @change="selectVideoClass"
                    >
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="到期时间" prop="expiration_time">
                    <el-date-picker
                        v-model="formData.expiration_time"
                        type="datetime"
                        :picker-options="pickerOptions"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        default-time="23:59:59"
                        @focus="handleFocus"
                        placeholder="选择到期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="视频文件" prop="videoUrl">
                    <uploadBtn @uploadSuccess="uploadSuccess($event)" v-bind:is_done="is_done" v-if="!disabled"></uploadBtn>
                    <div v-else>{{formData.videoUrl}}</div>
                </el-form-item>
                <el-form-item label="视频封面" prop="imageUrl">
                    <div class="header-img">
                        <el-upload
                            action="#"
                            :class="{'upload-box': true, 'local-hide': headerHideUpload }"
                            :http-request="handleUploadImg"
                            :file-list="imageList"
                            accept=".jpg, .png"
                            list-type="picture-card"
                            :multiple="false"
                            :limit="1"
                            :on-change="selectFile"
                            :on-remove="removeFile">
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                        <div class="el-upload__tip">
                            <p style="line-height:200%">1. 建议图片像素326*440、652*880（px）
                            <br>2. 图片格式 jpg, png
                            <br>3. 图片大小不超过2M</p>
                        </div>
                    </div>
                </el-form-item>
                 <el-form-item label="客服配置" prop="staff_id">
                    <el-input style="width:200px" autocomplete="off" v-model.number="formData.staff_id" placeholder="输入员工ID"></el-input>
                </el-form-item>
              <el-form-item label="关联品牌" prop="videoClassId">
                        <el-select v-model="brandarr_id"  clearable filterable  placeholder="选择品牌" @change="changeBrand(0,'change')">
                        <el-option v-for="(item, index) in brandArr" :key="index" :label="`${item.brand_initial} ${item.brand_name}`" :value="item.brand_id"></el-option>
                        </el-select>
                </el-form-item>
                    <el-form-item label="关联厂商" prop="videoClassId" >
                       <el-select  v-model="selectBrand_id" clearable placeholder="选择厂商" @change="changeBrand(1,'change')">
                        <el-option v-for="(item, index) in brand" :key="index" :label="item.brand_name" :value="item.brand_id"></el-option>
                        </el-select>
                </el-form-item>
                    <el-form-item label="关联车款" prop="videoClassId" >
                       <el-select  v-model="basebrand_id" clearable placeholder="选择车款" >
                        <el-option v-for="(item, index) in baseBrandSubList" :key="index" :label="item.brand_name" :value="item.brand_id"></el-option>
                        </el-select>
                </el-form-item>
              

                <!-- <el-form-item label="客服配置" prop="staff_id">
                    <el-input autocomplete="off" v-model.number="formData.staff_id" placeholder="输入员工ID"></el-input>
                </el-form-item> -->
                <el-form-item position="right">
                    <el-button type="primary" @click="submitForm('uploadVideo')" class="btnSave">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { brandModel } from "../api"
import uploadBtn from "./video-upload-btn.vue"
import { dateFormatter } from "@/common/js/util"
import upload from "./upload"
export default {
    components: { uploadBtn },
    name: "uploadVideo",
    data() {
        return {
            videoFormVisible: false, //上传视频页面是否显示
            formData: {
                videoTitle: "",
                videoUrl: "",
                imageUrl: "",
                videoClassId: '1',
                staff_id: '',
                expiration_time: null // 到期时间
            },
            rules: {
                videoTitle: [
                    { required: true, message: "请输入标题名称", trigger: "blur" },
                ],
                videoUrl: [
                    { required: true, message: "请上传视频", trigger: "change" },
                ],
                /*
                expiration_time: [
                    { required: true, message: "请选择到期时间", trigger: "change" },
                ],*/
                imageUrl: [
                    { required: true, message: "请上传视频封面", trigger: "blur" },
                ],
            },
            options: [],
            pickerOptions: {
                disabledDate: time => {
                    return (time.getTime() + 8.64e7) < Date.now()
                },
                selectableRange: `00:00:00 - 23:59:59`
            },
            imageList: [], //图片文件列表
            headerHideUpload: false,
            is_done: false,
            disabled: false,
            type: "add",
            videoID: 0,
            row: null,
            brandArr: [], // 品牌分类,
            brandarr_id:'',
            selectBrand_id:'',
            brand: [],
            basebrand_id:'',
            baseBrandSubList:[]
        };
    },
    watch: {
        "formData.expiration_time"(val, oldVal) {
            this.handleFocus(val)
        }
    },
    methods: {
        getOptions() {
          brandModel.getsVideoClass().then(res => {
            if (res.code == 1 && res.data) {
              this.options = res.data.map(item => ({value: item.id, label: item.video_class_name, sort: item.sort})).sort(function(a, b){  
                if (a.sort < b.sort) {  
                  return -1 
                } else if (a.sort > b.sort){  
                  return 1 
                }  
                return 0
              })
            }
          })
        },
        handleFocus(val = null) {
            if(!val) val = this.formData.expiration_time
            const date1 = new Date(val)
            const date2 = new Date()
            if(date1.getFullYear() + '-' + date1.getMonth() + '-' + date1.getDate() == 
            date2.getFullYear() + '-' + date2.getMonth() + '-' + date2.getDate()) {
                date2.setMinutes(date2.getMinutes() + 1) // 设置+1分钟
                this.pickerOptions.selectableRange = dateFormatter("hh:mm:ss", date2) + " - 23:59:59"
            } else {
                this.pickerOptions.selectableRange = "00:00:00 - 23:59:59"
            }
        },
        init(type = 'video_class', row = {}) {   
        
            if(type == 'video_edit') {
                this.formData = {
                    videoTitle: row.title,
                    videoUrl: row.video_url,
                    imageUrl: row.image_url,
                    expiration_time: row.expiration_time,
                    staff_id: row.staff_id,
                    videoClassId: row.video_class
                }

               this.getbranddetail(row.id)
                this.imageList = [{url: row.image_url, imageUrl: row.image_url}]
                this.headerHideUpload = true;
                this.disabled = true;
                this.type = "edit"
                this.videoID = row.id;
                this.row = row;
            } else {
                    this.videoFormVisible = true;
                this.formData = {
                    videoTitle: "",
                    videoUrl: "",
                    imageUrl: "",
                    staff_id: "",
                    expiration_time: null,
                    videoClassId: '1'
                }
                this.basebrand_id='';
                this.brandarr_id='';
                this.selectBrand_id='';
            }
        },
        getCarBrand(){
             this.$http.post('/admin/store/index.php?act=getBrand&op=selectBrand', {fid: 1}).
                then(res => {
                    this.brandArr = res || [];
                })
        },
          getbranddetail(id){
             this.$http.get('/admin/yt_car/index.php?act=yt_car&op=getVideoDetail&id='+id).
                then(res => {
                    if(res.code==1){
                     if(res.data.brand_id==0){
                            this.brandarr_id = '';
                            this.selectBrand_id = '';
                            this.basebrand_id = '';
                            this.videoFormVisible = true;
                        }else{
                            this.brandarr_id = res.data.brand_id_1;
                            this.selectBrand_id = res.data.brand_id_2;
                            this.basebrand_id = res.data.brand_id_3;
                            this.changeBrand(0,'base')
                            this.changeBrand(1,'base')
                        }
                    }else{
                        this.$message.error(res.msg)
                    }
                 
                })
        },
           // 品牌选择
            changeBrand(index,flag) {
                if(flag=='change'){
                  this.basebrand_id='';
                }
          
            if(index == 0) {
                if(flag=='change'){
                  this.selectBrand_id='';
                }
                this.$http.post('/admin/store/index.php?act=getBrand&op=selectBrand', {fid: this.brandarr_id}).
                then(res => {
                  this.brand = res || [];
                })
            } else if(index == 1) {
              this.$http.post('/admin/yt_car/index.php?act=yt_car&op=getBrandSubList', {
                brand_id: this.selectBrand_id
            }).then(res => {
                   this.baseBrandSubList=res.data;
                   if(flag=='base'){
                      this.videoFormVisible = true;
                   }
                })
            }
            },
        submitForm(formName) {
            // console.log(this.formData);
            //提交配置数据
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const time = new Date(dateFormatter("YYYY-MM-DD hh:mm", this.formData.expiration_time)).getTime()
                    const time2 = new Date(dateFormatter("YYYY-MM-DD hh:mm")).getTime()
                    if(time <= time2) {
                        this.$message.error("到期时间必须 > 当前时间，精确到分")
                        return false
                    }
                    // 添加
                    if(this.type == "add") {
                        let checked = this.checkFile(this.formData.imageUrl);
                        if (checked) {
                            let data = {
                                brand_id: this.carTypeId,
                                video_url: this.formData.videoUrl,
                                image_url: this.imageList && this.imageList[0] && this.imageList[0].imageUrl,
                                title: this.formData.videoTitle,
                                video_class: this.formData.videoClassId,
                                expiration_time: this.formData.expiration_time,
                                staff_id: this.formData.staff_id
                            }
                            brandModel.saveVideoUrl(data).then(res=>{
                                if(res.code===1){
                                    this.videoFormVisible = false;
                                    this.$message.success(res.msg);
                                    this.resetForm("uploadVideo");
                                    this.$parent.getList()
                                }else{
                                    this.$message.error(res.msg)
                                }
                            });
                        }
                    } else {
                        let data = {
                            v_id: this.videoID,
                            title: this.formData.videoTitle,
                            image_url: this.imageList && this.imageList[0] && this.imageList[0].imageUrl,
                            expiration_time: this.formData.expiration_time,
                            video_class: this.formData.videoClassId,
                            staff_id: this.formData.staff_id
                        }
                        console.log(this.basebrand_id)
                        if(this.basebrand_id==''&& this.brandarr_id){
                        this.$message.error("请选择相应车款")
                        return false
                        }
                        data.brand_id=this.basebrand_id;
                        data.image_url = data.image_url.replace('https://i.mycjj.com/', '')
                        brandModel.updateVideoInfo(data).then(res => {
                            if(res.code === 1){
                                this.$message.success("修改成功")
                                /*this.row.title = this.formData.videoTitle;
                                this.row.expiration_time = this.formData.expiration_time;
                                this.row.video_class = this.formData.videoClassId;
                                this.row.staff_id = this.formData.staff_id;
                                */
                                this.videoFormVisible = false;
                                this.resetForm("uploadVideo");
                                this.$parent.getList()
                            }else{
                                this.$message.error(res.msg)
                            }
                        });
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.imageList = [];
            this.headerHideUpload = false;
            this.is_done = false;
            this.disabled = false;
            this.type = "add";
            this.videoID = 0;
            this.row = null;
        },
        handleClose(close) {
            this.$confirm("关闭后数据不会保存！确认关闭？")
                .then((_) => {
                    this.resetForm("uploadVideo");
                    close();
                })
                .catch((_) => { });
        },
        //选择视频分类
        selectVideoClass(value) {
            this.formData.videoClassId = value
            //this.getList();
        },
        uploadSuccess(val) {
            //视频回调
            this.formData.videoUrl = val
        },
        //选择图片的回调
        selectFile(file, imageList) {
            this.imageList = imageList;
            this.headerHideUpload = imageList.length >= 1;
            this.formData.imageUrl = file.raw;
        },
        //删除图片的回调
        removeFile(file, imageList) {
            this.imageList = imageList;
            this.headerHideUpload = imageList.length >= 1;
            this.formData.imageUrl = "";
        },
        //上传前检查文件
        checkFile(file) {
            const isJPG = file.type === "image/jpeg";
            const isPng = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPng) {
                this.$message.error("上传图片只能是 JPG、PNG 格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
            }
            return true;
        },
        async handleUploadImg(file) {
            let rep = await upload(
                `/admin/yt_car/index.php?act=yt_car&op=uploadSeriesImage&brand_id=video_class`,
                file
            );
            if (rep.code === 200) {
                this.imageList.map((image) => {
                    if (image.uid == file.file.uid) {
                        image.imageUrl = rep.data.filename;
                    }
                });
            }
        },
    },
    created() {
        this.getOptions();
        this.getCarBrand()
    },
  computed: {
    getCarBrandOptions() {
      return function(index = 0) {
        return this.brandArr[index].details;
      }
    }
  },
    mounted() { },
};
</script>

<style lang="scss">
.el-dialog.hot-video-dialog {
    .el-dialog__header {
        padding-bottom: 5px;
    }
    .el-dialog__body {
        padding: 10px 10px;
    }
    .el-divider--horizontal {
        margin-top: 0px;
    }
    .el-form {
        padding-right: 10px;
    }
    .btnSave {
        float: right;
        margin-right: 5px;
        width: 88px;
    }
    .header-img {
        display: flex;
        .el-upload-list--picture-card .el-upload-list__item,
        .el-upload--picture-card {
            width: 100px;
            height: 130px;
        }
        .el-upload-list--picture-card {
            .el-upload-list__item {
                margin: 0;
                display: block;
            }
            .el-upload-list__item-status-label {
                display: none;
            }
        }
        .el-upload--picture-card {
            line-height: 130px;
            i {
                font-size: 20px;
            }
        }
        .local-hide .el-upload--picture-card {
            display: none;
        }
        .el-upload__tip {
            display: flex;
            align-items: center;
        }
    }
    .el-upload__tip {
        margin: 0 0 0 12px;
        display: inline-block;
    }
}
</style>